package com.FileManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Map;

import org.apache.struts2.json.annotations.JSON;

import com.Tool.RandomStringCreater;

public class Uploader extends Basic{
	private static final long serialVersionUID = 1L;
	/**
	 * @title Uploader.java
	 * @package com.logistics.File
	 * @author ufo
	 */

	private String savePath;

	public String upload(){
		try {
			if(isOnline()){
				addSessionToUser();
				FileOutputStream fos=null;
				String name;
				boolean flag=true;
				do{
					name=RandomStringCreater.createWithLettersAndNumbers(8)+user.getId();
					if(!(new File(getSavePath()+name).exists())){
						fos=new FileOutputStream(getSavePath()+name);
						flag=false;
					}
				}while(flag);
				FileInputStream fis=new FileInputStream(getFile());
				byte[] buffer=new byte[1024];
				int len=0;
				while((len=fis.read(buffer))>0)
					fos.write(buffer,0,len);

				result.put("flag", "true");
			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			result.put("flag", "false");
		}
		return SUCCESS;
	}
	public boolean isOnline(){
		if(request.getSession().getAttribute("userId")!=null)
			return true;
		else 
			return false;
	}
	public InputStream echo() {
		return inputStream;
	}
	@Override
	@JSON(name = "result")
	public Map<String, String> getResult() {
		// TODO 自动生成的方法存根
		return result;
	}
	public String getSavePath() {
		return savePath;
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
}
